package com.fish.admin.module.auth.strategy;

import cn.hutool.core.map.MapUtil;
import com.fish.admin.annotation.UserTypeAnnotation;
import com.fish.common.core.enums.UserTypeEnum;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;
@Component
public class AuthStrategyManager implements ApplicationContextAware {

    private static Map<UserTypeEnum, Class<AuthStrategy>> authStrategyMap = MapUtil.newConcurrentHashMap();
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AuthStrategyManager.applicationContext = applicationContext;
        //比较平易近人的写法
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(UserTypeAnnotation.class);
        beans.entrySet().forEach(e -> {
            String beanName = e.getKey();
            Class<AuthStrategy> authStrategyClass =  (Class<AuthStrategy>) beans.get(beanName).getClass();
            UserTypeEnum userType =  authStrategyClass.getAnnotation(UserTypeAnnotation.class).value();
            authStrategyMap.put(userType, authStrategyClass);
        });

    }

    /**
     * 通过类型拿到实例化的对象
     * @param userType
     * @return
     */
    public AuthStrategy authStrategy(UserTypeEnum userType) {
        Class<AuthStrategy> authStrategyClass = authStrategyMap.get(userType);
        if (ObjectUtils.isEmpty(authStrategyClass)) {
            throw new IllegalArgumentException("没有指定类型");
        }
        return applicationContext.getBean(authStrategyClass);
    }

}
